<?php

namespace app\admin\controller\wx;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Db;
use app\admin\model\Type;

/**
 * @icon fa fa-circle-o
 */
class Amoy extends Backend
{
    
    /**
     * Amoy模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Amoy');

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $where = array();
            $where['t.category'] = array('eq', 1);
            $where['a.is_show'] = array('eq', 1);
            $inputData = input();
            $filter = json_decode($inputData['filter'], true);
            if(!empty($filter['amoy_sn'])) {
                $where['a.amoy_sn'] = array('eq', $filter['amoy_sn']);
            }
            if(!empty($filter['user_name'])) {
                $where['u.user_name'] = array('eq', $filter['user_name']);
            }
            if(!empty($filter['type_name'])) {

                $where['t.type_id'] = array('eq', $filter['type_name']);
            }
            if(!empty($filter['role'])) {
                $where['a.role'] = array('eq', $filter['role']);
            }
            if(!empty($filter['is_show'])) {
                $where['a.is_show'] = array('eq', $filter['is_show']);
            }
            if(!empty($filter['add_time'])) {
                $date = explode(',', $filter['add_time']);
                foreach($date as &$v){
                    $v = strtotime($v);
                }
                $where['a.add_time'] = array('between', $date);
            }
            if(!empty($filter['nickname'])){
                $where['u.nickname|u.full_name'] =  array('like', "%{$filter['nickname']}%");
            }
            if(!empty($filter['user_name'])){
                $where['u.user_name'] =  array('eq', $filter['user_name']);
            }
            if(!empty($filter['content'])){
                $where['a.auto_content'] =  array('like', "%{$filter['content']}%");
            }
            if(!empty($filter['reward'])){
                if($filter['reward']==1){
                    $where['a.click_pay']=array('neq',0);
                }elseif($filter['reward']==2){
                    $where['a.see_pay']=array('neq',0);
                }elseif($filter['reward']==3){
                    $where['a.reward']=array('neq',0);
                }
            }
            $total = $this->model
                ->alias('a')
                ->join('cy_type t ', 'a.type_id = t.type_id')
                ->join('users u', 'a.user_id = u.user_id')
                ->where($where)
                ->order('a.amoy_id DESC')
                ->count();
            
            $fields = "t.type_name AS type_name,a.amoy_sn, a.amoy_id, a.user_id, a.type_id, a.role, a.auto_content, a.free_content, a.add_time, a.up_time, a.is_show,
            a.click_pay, a.click_unit_price, a.click_amount, a.see_pay, a.see_start_time, a.see_end_time, a.cash_deposit, a.reward, a.total_price,
            a.mission_status, u.nickname, u.user_name, u.full_name";
            
            $list = $this->model
                ->alias('a')
                ->join('cy_type t ', 'a.type_id = t.type_id')
                ->join('users u', 'u.user_id = a.user_id')
                ->field($fields)
                ->where($where)
                ->order('a.amoy_id DESC')
                ->limit($offset, $limit)
                ->select();
            //查找联系电话和手机号，
            $where_op['option_name']=array('like','%联系电话%');
            $where_op['is_delete']=0;
            $option=DB::name('option')
                ->where($where_op)
                ->whereor(['option_name'=>array('like','%手机号%')])
                ->select();
            $option_id=array();
            foreach ($option as $o){
                $option_id[]=$o['option_id'];
            }
            $reward=array('0'=>'未接单','1'=>'已接单','2'=>'已完成','3'=>'已取消');
            //查找联系电话和手机号对应OPTION的ID
            $where_amoy_data['option_id']=array('in',$option_id);
            foreach($list as &$v) {
                switch($v['role']) {
                    case 1:
                        $v['role'] = '自发';
                        break;
                    case 2:
                        $v['role'] = '代发';
                        break;
                    default:
                        $v['role'] = '默认';
                        break;
                }
                $where_amoy_data['amoy_id']=$v['amoy_id'];
                $v['tel']=DB::name('amoy_data')->where($where_amoy_data)->value('content');
                $v['add_time'] = date('Y/m/d H:i', $v['add_time']);
                $v['is_show'] = $v['is_show']==1?'显示':'不显示';
                $v['click_pay'] = $v['click_pay']?'有':'无';
                $v['see_pay'] = $v['see_pay']?'有':'无';
                $see_pay_start = $v['see_start_time']?date('Y/m/d H:i', $v['see_start_time']):'';
                $see_pay_end = $v['see_end_time']?date('Y/m/d H:i', $v['see_end_time']):'';
                $v['see_pay_time'] = $see_pay_start . "\n\r" . $see_pay_end;
                //点击次数
                $v['click_num']=DB('user_echarge')->where('user_note','like','%有偿点击收入,编号:'.$v['amoy_sn'].'%')->count();
                //剩余次数
                if($v['click_amount']!=0.00 && $v['click_unit_price']!=0.00){
                    $v['click_pay_times']=($v['click_amount']/$v['click_unit_price'])-$v['click_num'];
                }

               // $v['reward'] = $v['reward']?'有':'无';
                //$v['mission_status'] = $v['mission_status']==1?'进行中':'已结束';
                if($v['reward']){
                    $v['reward']='有';
                    $v['mission_status']=$reward[$v['mission_status']];
                }else{
                    $v['reward']='无';
                    $v['mission_status']='-';
                }
                $v['content'] = $v['auto_content'] . $v['free_content'];
            }
            unset($v);

            $result = array("total" => $total, "rows" => $list);
            
            return json($result);
        }

        //设置列表工具栏
        $btns = array('refresh', '');
        $this->view->assign('btns', $btns);
        
        //查询信息分类
        $typeModel = model('Type');
        $types = $typeModel->getType();
        $types = json_encode($types, JSON_UNESCAPED_UNICODE);
        $this->view->assign('types', $types);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add(){
        
        if ($this->request->isPost()) {
//            $params = $this->request->post("row/a");
            
            $type_name = input('type_name');
            $type_tpl = input('type_tpl');
            if(empty($type_name)){
                $this->error("信息分类名称不能为空");
            }
            
            // 插入单个记录
            Db::name('type')->insert(['type_name' => $type_name, 'type_tpl' => $type_tpl]);
            // 获取上次写入的自增Id
            $type_id = Db::getLastInsID();
            
            if(empty($type_id)){
                $this->error("添加失败");
            }
            $inputData = input();
            $type_num = $inputData['type_num'];
            $option_name = $inputData['option_name'];
            $option_type = $inputData['option_type'];
            $data_list = $inputData['data_list'];
            $is_show_name = $inputData['is_show_name'];
            $is_must = $inputData['is_must'];
            $option_holder = $inputData['option_holder'];
            $option_notes = $inputData['option_notes'];
            $is_self = $inputData['is_self'];
            $self_suffix = $inputData['self_suffix'];
            $option_id_arr = array();
            
            $OptionModel = Db::name('option');
            
            $error = "";
            
            foreach($type_num as $k=>$v){
                $a = $k+1;
                if(empty($option_name[$k])){
                    $error = "请选填写信息【".$a."】的名称";
                    break;
                }
                if(empty($option_type[$k]) && $option_type[$k] != "0"){
                    $error = "请选择信息【".$a."】的类型";
                    break;
                }
                if(in_array($option_type[$k],array(2,3)) && empty($data_list[$k])){
                    $error = "请填写信息【".$a."】的选项";
                    break;
                }
            }
            if(!empty($error)){
                $this->error($error);
            }
            $ListModel = Db::name('option_list');
            foreach($type_num as $key=>$num){
                $data = array();
                $data['type_id'] = $type_id;
                $data['num'] = $num;
                $data['option_name'] = $option_name[$key];
                $data['option_type'] = $option_type[$key];
                
                $data['is_show_name'] = $is_show_name[$key] ? $is_show_name[$key] : 1;
                $data['is_must'] = $is_must[$key] ? $is_must[$key] : 0;
                $data['option_holder'] = $option_holder[$key] ? $option_holder[$key] : '';
                $data['option_notes'] = $option_notes[$key] ? $option_notes[$key] : "";
                $data['is_self'] = $is_self[$key] ?  $is_self[$key] : 0;
                $data['self_suffix'] = $self_suffix[$key] ? $self_suffix[$key] : "";
                
                if(empty($option_id_arr[$key])){
//                    $data['option_id'] = $OptionModel->add($data);
                    $OptionModel->insert($data);
                    $data['option_id'] = Db::getLastInsID();
                }
                else{
                    $data['option_id'] = $option_id_arr[$key];
//                    $OptionModel->save($data);
                    $OptionModel->update($data);
//                    $ListModel->where(array("option_id"=>$data['option_id']))->delete();
                    $ListModel->where('option_id', $data['option_id'])->delete();
                }
                if(in_array($data['option_type'],array(2,3))){
                    $list_array = explode("|",$data_list[$key]);
                    $option_list = array();
                    foreach($list_array as $name){
                        $option_list[] = array("option_id"=>$data['option_id'],"list_name"=>$name);
                    }
                    $ListModel->insertAll($option_list);
                }
            }
            $option_del = input("del_option");
            if(!empty($option_del) && is_array($option_del)){
//                $OptionModel->where(array("option_id"=>array("in",$option_del)))->setField("is_delete",1);
                $OptionModel->where('option_id', 'in', $option_del)->update(['is_delete' => 1]);
            }
            $this->success("操作成功");
        } else {
            $this->view->assign('option_count', 0);
            $this->view->assign('option_list', array());
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $type_id = $ids;
        $type_info = Db::name('type')->where(array("is_delete" => 0,"type_id" => $type_id))->find();
        
        $option_list = Db::name('option')->where(array("is_delete" => 0,"type_id" => $type_id))->order("num ASC,option_id ASC")->select();
        
        foreach($option_list as  $key=>$val){
            $data_list = Db('option_list')->where(array("option_id" => $val['option_id']))->column("list_name");
            if(!empty($data_list)){
                $option_list[$key]['data_list'] = implode("|",$data_list);
            }
        }
        $option_count = Db::name('option')->where(array("type_id"=>$type_id))->max("num");
        $option_count = $option_count ? $option_count : 0;
        
        $this->view->assign("option_count",$option_count);
        $this->view->assign("type_info",$type_info);
        $this->view->assign("option_list",$option_list);
        
        if ($this->request->isPost()) {
            $type_name = input('type_name');
            $type_tpl = input('type_tpl');
            if(empty($type_name)){
                $this->error("信息分类名称不能为空");
            }
            if($type_id){
                Db::name('type')->where(array("is_delete" => 0,"type_id" => $type_id))->update(array("type_name" => $type_name,'type_tpl' => $type_tpl));
            }
            
            if(empty($type_id)){
                $this->error("添加失败");
            }
            
            $inputData = input();
            $type_num = $inputData['type_num'];
            $option_name = $inputData['option_name'];
            $option_type = $inputData['option_type'];
            $data_list = $inputData['data_list'];
            $is_show_name = $inputData['is_show_name'];
            $is_must = $inputData['is_must'];
            $option_holder = $inputData['option_holder'];
            $option_notes = $inputData['option_notes'];
            $is_self = $inputData['is_self'];
            $self_suffix = $inputData['self_suffix'];
            $option_id_arr = $inputData['option_id'];
            
            $OptionModel = Db::name('option');
            
            $error = "";
            
            foreach($type_num as $k=>$v){
                $a = $k+1;
                if(empty($option_name[$k])){
                    $error = "请选填写信息【".$a."】的名称";
                    break;
                }
                if(empty($option_type[$k]) && $option_type[$k] != "0"){
                    $error = "请选择信息【".$a."】的类型";
                    break;
                }
                if(in_array($option_type[$k],array(2,3)) && empty($data_list[$k])){
                    $error = "请填写信息【".$a."】的选项";
                    break;
                }
            }
            if(!empty($error)){
                $this->error($error);
            }
            
            $ListModel = Db::name('option_list');
            foreach($type_num as $key=>$num){
                $data = array();
                $data['type_id'] = $type_id;
                $data['num'] = $num;
                $data['option_name'] = $option_name[$key];
                $data['option_type'] = $option_type[$key];
                
                $data['is_show_name'] = $is_show_name[$key] ? $is_show_name[$key] : 1;
                $data['is_must'] = $is_must[$key] ? $is_must[$key] : 0;
                $data['option_holder'] = $option_holder[$key] ? $option_holder[$key] : '';
                $data['option_notes'] = $option_notes[$key] ? $option_notes[$key] : "";
                $data['is_self'] = $is_self[$key] ?  $is_self[$key] : 0;
                $data['self_suffix'] = $self_suffix[$key] ? $self_suffix[$key] : "";
                
                if(empty($option_id_arr[$key])){
                    $OptionModel->insert($data);
                    $data['option_id'] = Db::getLastInsID();
                } else {
                    $data['option_id'] = $option_id_arr[$key];
                    $OptionModel->update($data);
                    $ListModel->where('option_id', $data['option_id'])->delete();
                }
                
                if(in_array($data['option_type'],array(2,3))){
                    $list_array = explode("|",$data_list[$key]);
                    $option_list = array();
                    foreach($list_array as $name){
                        $option_list[] = array("option_id"=>$data['option_id'],"list_name"=>$name);
                    }
                    $ListModel->insertAll($option_list);
                }
            }
            
            if(isset($inputData['del_option'])) {
                $option_del = $inputData['del_option'];
                if(!empty($option_del) && is_array($option_del)){
                    $OptionModel->where('option_id', 'in', $option_del)->update(['is_delete' => 1]);
                }
            }
            
            $this->success("操作成功");
        }
        
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = ""){
        $amoy_id = $ids;
        $re = $this->model->save(['is_show'=> 0], ['amoy_id' => $amoy_id]);
        if($re){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    /**
     * 手机链接
     */
    public function mobile_url($ids = ""){
        $amoy_id = $ids;
        $kind = $this->model->where('amoy_id', $amoy_id)->value('kind');
        $url = 'http://moments.taoxiansheng.com/?#/';
        switch ($kind){
            case 'information':
                $url .= 'information/detail/' . $amoy_id;
                break;
            case  'mission':
                $url .= 'task/detail/' . $amoy_id;
            case  '':
                $url .='article/detail/' . $amoy_id;
        }
        $this->view->assign('mobile_url', $url);

        return $this->view->fetch();
    }
    /**
     * 手机链接简历
     */
    public function resume_url($ids = ""){

        $url = 'http://moments.taoxiansheng.com/?#/service/talent_pool/resume_detail/'.$ids;
        $this->view->assign('mobile_url', $url);
        return $this->view->fetch();
    }
}
